package com.mtk.launcher.power.util;

import android.content.Context;

import com.mtk.launcher.power.bean.PowerLogEntity;
import com.mtk.launcher.power.bean.ScheduleRecord;
import com.mtk.launcher.power.bean.TimeDealEntity;
import com.mtk.launcher.power.bean.TimeLocalEntity;
import com.lark.wifi.util.MyLog;

import org.litepal.LitePal;

import com.mtk.launcher.util.SimpleDateUtil;
import com.mtk.launcher.util.shared.SharedPerManager;

import java.util.ArrayList;
import java.util.List;

public class PowerOnOffUtil {

    Context context;
    List<ScheduleRecord> listPowerOnOff = new ArrayList<>();

    public PowerOnOffUtil(Context context) {
        this.context = context;
    }

    public static boolean clearAllPowerOnOff(String printTag) {
        LitePal.deleteAll(TimeLocalEntity.class);
        SharedPerManager.setPowerOnOffTime(null, printTag);
        return true;
    }

    public static List<TimeLocalEntity> queryTimerList() {
        List<TimeLocalEntity> list = LitePal.findAll(TimeLocalEntity.class);
        return list;
    }

    public boolean addTimerDb(TimeLocalEntity timeLocalEntity) {
        if (timeLocalEntity == null) {
            logInfo("addTimerDb: timeLocalEntity == null");
            return false;
        }
        List<TimeLocalEntity> timeLocalEntityList = queryTimerList();
        logInfo("addTimerDb=检测数据库列表==" + timeLocalEntityList);
        if (timeLocalEntityList == null || timeLocalEntityList.size() < 1) {
            logInfo("addTimerDb=直接添加数据==" + timeLocalEntity);
            return timeLocalEntity.save();
        }
        String saveOnTime = timeLocalEntity.getTtOnTime();
        String saveOffTime = timeLocalEntity.getTtOffTime();
        boolean hasSameInfo = false;
        for (TimeLocalEntity timeCache : timeLocalEntityList) {
            String onTime = timeCache.getTtOnTime();
            String offTime = timeCache.getTtOffTime();
            if (onTime.equals(saveOnTime)
                    && offTime.equals(saveOffTime)
                    && timeLocalEntity.getTtMon().equals(timeCache.getTtMon())
                    && timeLocalEntity.getTtTue().equals(timeCache.getTtTue())
                    && timeLocalEntity.getTtWed().equals(timeCache.getTtWed())
                    && timeLocalEntity.getTtThu().equals(timeCache.getTtThu())
                    && timeLocalEntity.getTtFri().equals(timeCache.getTtFri())
                    && timeLocalEntity.getTtSat().equals(timeCache.getTtSat())
                    && timeLocalEntity.getTtSun().equals(timeCache.getTtSun())
            ) {
                //相同得数据
                hasSameInfo = true;
            }
        }
        if (hasSameInfo) {
            logInfo("addTimerDb=有相同得数据。不添加");
            return true;
        }
        logInfo("addTimerDb，没有相同得数据直接添加");
        return timeLocalEntity.save();
    }

    /***
     * 删除定时开关机
     * @param timerId
     */
    public static boolean delTimerById(String timerId) {
        int delInfo = LitePal.deleteAll(TimeLocalEntity.class, "timeId=?", timerId);
        if (delInfo > 0) {
            return true;
        } else {
            return false;
        }
    }

    public void changePowerOnOffByWorkModel(String printTag) {
        MyLog.powerOnOff("changePowerOnOffByWorkModel==" + printTag);
        clearSystemPowerOnOffTime("准备设置定时时间，先清理本地时间=" + printTag);
        List<TimeLocalEntity> lists = queryTimerList();
        if (lists == null || lists.size() < 1) {
            return;
        }
        setPowerOnOffTime(lists);
    }

    /**
     * 设置系统定时开关机
     * 定时开关机规律
     * 1：分组智能设定一组
     * 2：采取获取当前最近的一组，设定，
     * 3：下次开机重新获取离下次最近的一组
     *
     * @param lists
     */
    private void setPowerOnOffTime(List<TimeLocalEntity> lists) {
        try {
            listPowerOnOff.clear();
            if (lists.size() < 1) {
                clearSystemPowerOnOffTime("设置的时间列表《1，直接清理设置的时间");    //===清理定时开关机====
                MyLog.powerOnOff("获取的定时开关机 < 1 ,用户删除定时开关机任务，终止操作");
                return;
            }
            for (int i = 0; i < lists.size(); i++) {
                int dayOfWeek = -1;
                TimeLocalEntity entity = lists.get(i);
                String powerOnTime = entity.getTtOnTime();
                String powerOffTime = entity.getTtOffTime();
                if (powerOnTime.length() < 1 || powerOffTime.length() < 1) { //如果本次的数据为null，跳过本次循环
                    continue;
                }
                MyLog.powerOnOff("=====获取的开机关机时间===" + powerOffTime + " / " + powerOnTime);
                int onHour = Integer.parseInt(powerOnTime.substring(0, powerOnTime.indexOf(":")));
                int onMin = Integer.parseInt(powerOnTime.substring(powerOnTime.indexOf(":") + 1));
                int offHour = Integer.parseInt(powerOffTime.substring(0, powerOffTime.indexOf(":")));
                int offMin = Integer.parseInt(powerOffTime.substring(powerOffTime.indexOf(":") + 1));
                boolean ttMon = Boolean.parseBoolean(entity.getTtMon());
                if (ttMon) {
                    dayOfWeek = 2;
                    saveTimerTask(dayOfWeek, onHour, onMin, offHour, offMin);
                }
                boolean ttTue = Boolean.parseBoolean(entity.getTtTue());
                if (ttTue) {
                    dayOfWeek = 3;
                    saveTimerTask(dayOfWeek, onHour, onMin, offHour, offMin);
                }
                boolean ttWed = Boolean.parseBoolean(entity.getTtWed());
                if (ttWed) {
                    dayOfWeek = 4;
                    saveTimerTask(dayOfWeek, onHour, onMin, offHour, offMin);
                }
                boolean ttThu = Boolean.parseBoolean(entity.getTtThu());
                if (ttThu) {
                    dayOfWeek = 5;
                    saveTimerTask(dayOfWeek, onHour, onMin, offHour, offMin);
                }
                boolean ttFri = Boolean.parseBoolean(entity.getTtFri());
                if (ttFri) {
                    dayOfWeek = 6;
                    saveTimerTask(dayOfWeek, onHour, onMin, offHour, offMin);
                }
                boolean ttSat = Boolean.parseBoolean(entity.getTtSat());
                if (ttSat) {
                    dayOfWeek = 7;
                    saveTimerTask(dayOfWeek, onHour, onMin, offHour, offMin);
                }
                boolean ttSun = Boolean.parseBoolean(entity.getTtSun());
                if (ttSun) {
                    dayOfWeek = 1;
                    saveTimerTask(dayOfWeek, onHour, onMin, offHour, offMin);
                }
            }
            long powerOffTime = TSchedule.getLastPowerOnOffTime(listPowerOnOff, false);
            long powerOnTime = TSchedule.getLastPowerOnOffTime(listPowerOnOff, true);
//            MyLog.powerOnOff("===获取的关机时间===" + powerOffTime + " /最早的开机时间==" + powerOnTime);
            if (powerOffTime < 0 && powerOnTime < 0) {   //这里可能获取时间异常了 ，不设置定时开关机
                MyLog.powerOnOff("===获取的开关机时间异常了，这里清理定时开关机");
                clearSystemPowerOnOffTime("设置定时时间，数据异常了，这里清空数据");
                return;
            }
            if (powerOffTime > 0 && powerOnTime < 0) {
                //这里表示设置的开关时间已经超过一周了，这里需要做一个预判。第二天这个时候开机i一次，然后重新获取
                powerOnTime = TSchedule.jujleNoOnTime(powerOffTime);
            }
            MyLog.powerOnOff("=====最终的时间=开机时间==" + powerOnTime + " /当前时间 " + powerOffTime);
            long currentTimeSimple = SimpleDateUtil.getCurrentTimelONG(); //獲取當前的時間
            //如果下一次的定时开关机時間大於當前3分鐘，才能設定，不然就區下一次的定時開關機
            if (powerOnTime < powerOffTime && (powerOnTime - currentTimeSimple) > 300) {
                //如果最近的一次开机时间《关机时间，以最近的一次为准.倒退两分钟开机
                long onTimeLong = SimpleDateUtil.StringToLongTimePower(powerOnTime + "");
                long onTimeLongOff = onTimeLong - (1000 * 120);  //关机时间在此时间前减去2分钟再去换算时间
                MyLog.powerOnOff("===onTimeLongOff===" + onTimeLongOff);
                powerOffTime = SimpleDateUtil.formatBig(onTimeLongOff);
                MyLog.powerOnOff("===合理的时间===" + powerOnTime + " / " + powerOffTime);
                timeLongChangeEntitytoSetTime(powerOffTime, powerOnTime);
                return;
            }
            powerOnTime = TSchedule.getLastPowerOnTime(listPowerOnOff, powerOffTime);
            MyLog.powerOnOff("===获取的开机时间===" + powerOnTime);
            if (powerOffTime < 0 || powerOnTime < 0) {
                //这里可能获取时间异常了 ，不设置定时开关机
                MyLog.powerOnOff("===获取的开关机时间异常了，这里清理定时开关机");
                clearSystemPowerOnOffTime("又他妈数据异常了，清理数据");
                return;
            }
            timeLongChangeEntitytoSetTime(powerOffTime, powerOnTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 用来转化时间参数
     * 将long 类型的定时开关机转化成Entity 类型的数据
     *
     * @param powerOffTime
     * @param powerOnTime
     */
    private void timeLongChangeEntitytoSetTime(long powerOffTime, long powerOnTime) {
        MyLog.powerOnOff("===设定的关机时间===" + powerOffTime + " / " + powerOnTime);
        long offTimeSet = SimpleDateUtil.StringToLongTimePower(String.valueOf(powerOffTime));
        long onTimeSet = SimpleDateUtil.StringToLongTimePower(String.valueOf(powerOnTime));
//        MyLog.powerOnOff("===设定的关机时间==转换后=" + offTimeSet + " / " + onTimeSet);
        if (offTimeSet < 1000 || onTimeSet < 1000) {
            return;
        }
        TimeDealEntity timeDealEntity = new TimeDealEntity(powerOffTime, powerOnTime);
        SharedPerManager.setPowerOnOffTime(timeDealEntity, "设置定时开关机数据");
        String createTime = SimpleDateUtil.formatBig(System.currentTimeMillis()) + "";
        PowerLogEntity MyLogEntity = new PowerLogEntity(String.valueOf(powerOffTime), String.valueOf(powerOnTime), createTime);
        addTimerLogDb(MyLogEntity);
    }

    private void saveTimerTask(int dayOfWeek, int onHour, int onMin, int offHour, int offMin) {
        ScheduleRecord scheduleRecord = new ScheduleRecord(dayOfWeek, onHour, onMin, offHour, offMin);
        listPowerOnOff.add(scheduleRecord);
    }

    /***
     * 清理本地的定时开关机时间
     * @param printTag
     */
    private void clearSystemPowerOnOffTime(String printTag) {
        SharedPerManager.setPowerOnOffTime(null, printTag);
    }

    private void logInfo(String s) {
    }

    public boolean addTimerLogDb(PowerLogEntity powerLogEntity) {
        if (powerLogEntity == null) {
            logInfo("添加日志数据失败: timeLocalEntity == null");
            return false;
        }
        checkTimeListSize();
        return powerLogEntity.save();
    }

    /***
     * 检查多余得时间
     */
    public static void checkTimeListSize() {
        //设置最大条数
        int maxSize = 1001;
        List<PowerLogEntity> powerLogEntityList = LitePal.findAll(PowerLogEntity.class);
        if (powerLogEntityList == null || powerLogEntityList.size() < maxSize) {
            MyLog.cdl("checkTimeListSize < " + maxSize);
            return;
        }
        MyLog.cdl("checkTimeListSize=" + powerLogEntityList.size());
        //超过1000 条 ，就删除10条
        for (int i = 0; i < 10; i++) {
            PowerLogEntity powerLogEntity = powerLogEntityList.get(i);
            String timeSave = powerLogEntity.getCreateTime();
            boolean isDel = delTimerLogById(timeSave);
            MyLog.cdl("checkTimeListSize-isDel=" + isDel + " / " + timeSave);
        }
    }

    /***
     * 删除定时开关机日志
     * @param timerId
     */
    private static boolean delTimerLogById(String timerId) {
        int delInfo = LitePal.deleteAll(PowerLogEntity.class, "createTime = ?", timerId);
        if (delInfo > 0) {
            return true;
        } else {
            return false;
        }
    }


    /***
     * 获取日志集合
     * 无需理会，软件内部自动增删改查
     * @return
     */
    public static List<PowerLogEntity> getDbLogList() {
        return LitePal.findAll(PowerLogEntity.class);
    }

    /****
     * 清理所有的日志记录
     * @return
     */
    public static boolean clearAllTimeLogDb() {
        LitePal.deleteAll(PowerLogEntity.class);
        return true;
    }

}
